<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/9/1
 * Time: 14:17
 */

namespace App\Admin\Forms;

use App\Models\RechargeRecord;
use App\Models\Coupon;
use App\Models\UserCoupon;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;

class CouponProfile extends Form implements LazyRenderable
{
    use LazyWidget;

    public function handle(array $input)
    {
        $id = $this->payload['key'] ?? 0;
        $info = RechargeRecord::query()->find($id);
        $user_id = $info->user_id;
        $coupon_id = $input['id'];
        $this->grantActivityCoupon($user_id, $coupon_id);
        return $this->success('发放成功');
    }

    public function form()
    {

        $this->select('id', '优惠券')->required()
            ->options(Coupon::selectOption());
    }

    /**
     * 发放用户活动奖励
     * @param $user_id
     * @param $activity_id
     * @param int $company_id
     * @return bool
     */
    public function grantActivityCoupon(int $user_id, int $coupon_id)
    {
        $user_coupon_info = Coupon::query()->where('id', $coupon_id)->first(['id', 'validity_day']);
        $insert_data = [
            'user_id' => $user_id,
            'company_id' => 1,
            'activity_id' => 0,
            'coupon_id' => $coupon_id,
            'from' => 2, //来源 1-领取 2-系统发放
            'status' => 1,
            'receive_time' => time(),
            'overdue_time' => $user_coupon_info->validity_day ? time() + $user_coupon_info->validity_day * 86400 : 0
        ];
        return UserCoupon::query()->create($insert_data);
    }

}